package com.nondo.rdp.finance.service.impl;

import com.nondo.rdp.auth.domain.Role;
import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.finance.domain.UserAuth;
import com.nondo.rdp.finance.repository.UserAuthRepository;
import com.nondo.rdp.finance.service.UserAuthService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * DatabaseUserService
 *
 * @author linfeng
 * @since 2017/7/30
 */
@Service
@Transactional
public class UserAuthServiceImpl implements UserAuthService {
    @Autowired
    UserAuthRepository userAuthRepository;

    @Override
    public Page<UserAuth> findAll(Page<UserAuth> page, UserAuth analysis) {
        Sort sort = new Sort(Sort.Direction.DESC, "createDate");
        PageRequest pageRequest = new PageRequest(page.getPageNumber(), page.getPageSize(), sort);
        org.springframework.data.domain.Page<UserAuth> dictPage = userAuthRepository.findAll((root, query, builder) -> {

            List<Predicate> predicates = new ArrayList<>();

            //搜索标题
            if (StringUtils.isNotEmpty(analysis.getRealname())) {
                predicates.add(builder.like(root.get("realname"), "%" + analysis.getRealname() + "%"));
            }

            predicates.add(builder.equal(root.get("delFlag"), Role.DEL_FLAG_NORMAL));
            Predicate[] predicatesArray = new Predicate[predicates.size()];
            predicates.toArray(predicatesArray);
            return builder.and(predicatesArray);

        }, pageRequest);

        return new Page<UserAuth>(dictPage);
    }

    @Override
    public Optional<UserAuth> findByUser(User user) {
        return this.userAuthRepository.findByUser(user);
    }

    @Override
    public UserAuth save(UserAuth userAuth) {
        return this.userAuthRepository.save(userAuth);
    }

    @Override
    public void delete(Long id) {
        userAuthRepository.deleteById(id);
    }
}
